﻿using AutoMapper;
using ImoviesBlazor.Server.Repository;
using ImoviesBlazor.Shared.Dtos;
using ImoviesBlazor.Shared.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ImoviesBlazor.Server.Controllers
{

    /// <summary>
    /// 电影播放链接控制器
    /// </summary>
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class TeleplayVlinkController : ControllerBase
    {
        private readonly ITeleplayVlinkRepository _teleplayVlinkRepository;
        private readonly IMapper _mapper;

        public TeleplayVlinkController(ITeleplayVlinkRepository teleplayRepository, IMapper mapper)
        {
            this._teleplayVlinkRepository = teleplayRepository;
            this._mapper = mapper;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="teleplayVlink"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add([FromBody] TeleplayVlinkForCreateDto teleplayVlink)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var t = _mapper.Map<TeleplayVlink>(teleplayVlink);
            _teleplayVlinkRepository.AddTeleplayVlink(t);
            bool res = await _teleplayVlinkRepository.SaveAsync();
            if (!res)   //保存失败
            {
                Response.StatusCode = 500;
                return Content("操作失败");
            }
            return Ok();
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="teleplayVlink"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult> Update([FromBody] TeleplayVlinkForUpdateDto teleplayVlink)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var t = _mapper.Map<TeleplayVlink>(teleplayVlink);
            _teleplayVlinkRepository.UpdateTeleplayVlink(t);
            bool res = await _teleplayVlinkRepository.SaveAsync();
            if (!res)   //保存失败
            {
                Response.StatusCode = 500;
                return Content("操作失败");
            }
            return Ok();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete([FromRoute] uint id)
        {
            await _teleplayVlinkRepository.DeleteTeleplayVlink(id);
            bool res = await _teleplayVlinkRepository.SaveAsync();
            if (!res)   //保存失败
            {
                Response.StatusCode = 500;
                return Content("操作失败");
            }
            return Ok();
        }
    }
}
